package im.elephas.androfan;

import im.elephas.fanfouapi.FanfouApi;
import im.elephas.fanfouapi.events.IChangeEvent;
import im.elephas.fanfouapi.events.IErrorEvent;
import im.elephas.fanfouapi.events.IStatusesEvent;
import im.elephas.fanfouapi.items.StatusItem;
import im.elephas.util.DateFormater;
import im.elephas.util.ImageGetter;
import im.elephas.util.TagFilter;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class StatusesActivity extends Activity implements OnClickListener {

	private enum StatusesType {
		FRIENDS, USER, PUBLIC, REPLY
	}

	private LinearLayout linearLayout;
	private TextView refreshButton;
	private ProgressBar refreshProgressBar;
	private ImageView refreshImageView;
	private View refreshButtonView;
	private Button prevButton;
	private Button nextButton;
	private ScrollView scrollView;

	private FanfouApi mFanfouApi;

	private StatusesActivity mStatusesActivity = this;
	private StatusItem currentItem;

	private List<StatusItem> listStatusesItems;

	private boolean isGettingStatuses;
	private int page;
	private int count = 20;

	private StatusesType currentType = StatusesType.FRIENDS;

	private IErrorEvent mIErrorEvent = new IErrorEvent() {

		@Override
		public void errorHandler() {
			mStatusesActivity.runOnUiThread(statusesError);
		}
	};

	private IStatusesEvent mIStatusesEvent = new IStatusesEvent() {

		@Override
		public void statusesHandler(List<StatusItem> lsi) {
			listStatusesItems = lsi;
			mStatusesActivity.runOnUiThread(statusesRefresh);
		}
	};

	private Runnable statusesRefresh = new Runnable() {

		@Override
		public void run() {
			refreshStatuses();
		}
	};

	private Runnable statusesError = new Runnable() {
		@Override
		public void run() {
			Builder dialog = new AlertDialog.Builder(mStatusesActivity);
			dialog.setTitle("获取消息失败！请检查网络设置。");
			dialog.show();
			isGettingStatuses = false;
		}
	};

	private void changeStatusesType(StatusesType st) {
		setContentView(R.layout.statusesfreshing);
		currentType = st;
		page = 1;
		getStatuses();
	}

	private void getStatuses() {
		if (isGettingStatuses == true)
			return;
		isGettingStatuses = true;

		switch (currentType) {
		case FRIENDS:
			mFanfouApi.getFriendsTimeline(count, page, mIStatusesEvent,
					mIErrorEvent);
			break;
		case USER:
			mFanfouApi.getUserTimeline(count, page, mIStatusesEvent,
					mIErrorEvent);
			break;
		case PUBLIC:
			mFanfouApi.getPublicTimeline(count, mIStatusesEvent, mIErrorEvent);
			break;
		case REPLY:
			mFanfouApi.getReplyTimeline(count, page, mIStatusesEvent,
					mIErrorEvent);
			break;
		default:
			break;
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(refreshButtonView)) {
			refreshUnabled();
			getStatuses();
		}
		if (v.equals(prevButton)) {
			if (page > 1)
				page--;
			refreshUnabled();
			getStatuses();
		}
		if (v.equals(nextButton)) {
			page++;
			refreshUnabled();
			getStatuses();
		}
	}

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.statusesfreshing);

		mFanfouApi = FanfouApi.getInstance();

		page = 1;

		setTitle(mFanfouApi.getUser().getScreenName() + " 大家的消息");

		isGettingStatuses = false;
		getStatuses();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, 1, 1, "发送").setIcon(android.R.drawable.ic_menu_edit);
		menu.add(2, 2, 2, "消息")
				.setIcon(android.R.drawable.ic_menu_info_details);
		menu.add(2, 3, 3, "回复我的").setIcon(android.R.drawable.ic_menu_call);

		menu.add(2, 4, 4, "空间").setIcon(android.R.drawable.ic_menu_myplaces);
//		menu.add(3, 5, 5, "私信").setIcon(android.R.drawable.ic_menu_compass);
		menu.add(3, 6, 6, "随便看看").setIcon(android.R.drawable.ic_menu_view);
		menu.add(3, 7, 7, "收藏");
		menu.add(3, 8, 8, "关注我的");
		menu.add(3, 9, 9, "我关注的");
//		menu.add(3, 10, 10, "设置");
//		menu.add(3, 11, 11, "关于");
		menu.add(3, 12, 12, "退出");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			confirmQuitDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void confirmQuitDialog() {
		Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("确定退出?");
		dialog.setMessage("确定退出AndroFan?");
		dialog.setPositiveButton("退出", new Dialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		dialog.setNegativeButton("取消", null);
		dialog.show();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch (item.getItemId()) {
		case 1:
			i = new Intent(this, SendMessageActivity.class);
			startActivityForResult(i, 0);
			break;
		case 2:
			setTitle(mFanfouApi.getUser().getScreenName() + " 大家的消息");
			changeStatusesType(StatusesType.FRIENDS);
			break;
		case 3:
			setTitle(mFanfouApi.getUser().getScreenName() + " 回复我的消息");
			changeStatusesType(StatusesType.REPLY);
			break;
		case 4:
			setTitle(mFanfouApi.getUser().getScreenName() + " 我的空间");
			changeStatusesType(StatusesType.USER);
			getStatuses();
			break;
		case 5:
			break;
		case 6:
			setTitle(mFanfouApi.getUser().getScreenName() + " 随便看看");
			changeStatusesType(StatusesType.PUBLIC);
			break;
		case 7:
			i = new Intent(mStatusesActivity, FavoritesActivity.class);
			startActivityForResult(i, 0);
			break;
		case 8:
			i = new Intent(mStatusesActivity, FollowersActivity.class);
			startActivityForResult(i, 0);
			break;
		case 9:
			i = new Intent(mStatusesActivity, FriendsActivity.class);
			startActivityForResult(i, 0);
			break;
		case 10:
			break;
		case 11:
			break;
		case 12:
			confirmQuitDialog();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (!isGettingStatuses)
			refreshStatuses();
	}

	private void refreshStatuses() {
		setContentView(R.layout.statuses);

		linearLayout = (LinearLayout) findViewById(R.id.statusesLinearLayout);

		refreshButtonView = getLayoutInflater().inflate(
				R.layout.statusesbutton, null);
		refreshButtonView.setBackgroundColor(Color.argb(255, 202, 222, 235));
		linearLayout.addView(refreshButtonView);
		refreshButtonView.setClickable(false);
		refreshButtonView.setOnClickListener(this);

		refreshButton = (TextView) refreshButtonView
				.findViewById(R.id.statusesButton);
		refreshButton.setText("刷新");

		refreshProgressBar = (ProgressBar) findViewById(R.id.buttonProgressBar);
		refreshProgressBar.setVisibility(View.INVISIBLE);

		refreshImageView = (ImageView) findViewById(R.id.buttonImageView);
		refreshImageView
				.setImageResource(android.R.drawable.ic_menu_recent_history);
		refreshProgressBar.setVisibility(View.INVISIBLE);
		refreshImageView.setVisibility(View.VISIBLE);

		scrollView = (ScrollView) findViewById(R.id.statusesScrollView);

		boolean colorDark = false;
		for (final StatusItem item : listStatusesItems) {
			View view;
			OnClickListener listener;
			OnLongClickListener longListener;
			if (mFanfouApi.getUser().getId().equals(item.getUser().getId())) {
				view = getLayoutInflater().inflate(R.layout.statusesmyitem,
						null);
				longListener = new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						currentItem = item;
						showMySelectTextMenuDialog();
						return true;
					}
				};
				listener = new OnClickListener() {

					@Override
					public void onClick(View v) {
						currentItem = item;
						showMySelectTextMenuDialog();
					}
				};

			} else {
				view = getLayoutInflater().inflate(R.layout.statusesitem, null);
				longListener = new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						currentItem = item;
						showSelectTextMenuDialog();
						return true;
					}
				};
				listener = new OnClickListener() {

					@Override
					public void onClick(View v) {
						currentItem = item;
						showSelectTextMenuDialog();
					}
				};
			}
			if (colorDark)
				view.setBackgroundColor(Color.argb(255, 202, 222, 235));
			else
				view.setBackgroundColor(Color.argb(255, 237, 237, 237));
			colorDark = !colorDark;
			ImageView iv = (ImageView) view.findViewById(R.id.avatarImageView);
			TextView nameTextView = (TextView) view
					.findViewById(R.id.nameTextView);
			TextView statusTextView = (TextView) view
					.findViewById(R.id.statusTextView);
			TextView sourceTextView = (TextView) view
					.findViewById(R.id.sourceTextView);
			TextView timeTextView = (TextView) view
					.findViewById(R.id.timeTextView);
			iv.setImageBitmap(ImageGetter.getBitMap(item.getUser()
					.getProfileImageUrl()));

			nameTextView.setText(item.getUser().getName());
			statusTextView.setText(item.getText());
			sourceTextView.setText("通过: " + TagFilter.getTag(item.getSource()));
			timeTextView.setText(DateFormater.formatDate(item.getCreatedAt()));

			linearLayout.addView(view);
			view.setClickable(true);
			iv.setClickable(true);

			view.setOnLongClickListener(longListener);
			iv.setOnClickListener(listener);
			statusTextView.setOnLongClickListener(longListener);
		}

		View view = getLayoutInflater().inflate(R.layout.statusespages, null);
		linearLayout.addView(view);
		prevButton = (Button) findViewById(R.id.prevButton);
		nextButton = (Button) findViewById(R.id.nextButton);
		prevButton.setOnClickListener(this);
		nextButton.setOnClickListener(this);

		if (page > 1)
			prevButton.setEnabled(true);

		isGettingStatuses = false;
	}

	private void refreshUnabled() {
		refreshButtonView.setClickable(false);
		refreshProgressBar.setVisibility(View.VISIBLE);
		refreshImageView.setVisibility(View.INVISIBLE);
		prevButton.setEnabled(false);
		nextButton.setEnabled(false);
	}

	private void showSelectTextMenuDialog() {
		Builder dialog = new AlertDialog.Builder(this);
		String[] sel = { "回复", "收藏", "查看资料" };
		dialog.setTitle("对@" + currentItem.getUser().getScreenName());
		dialog.setItems(sel, new Dialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent i;
				Bundle b;
				switch (which) {
				case 0:
					i = new Intent(mStatusesActivity, SendMessageActivity.class);
					b = new Bundle();
					b.putBoolean("isreply", true);
					b.putString("atname", currentItem.getUser().getName());
					b.putString("replyid", currentItem.getUser().getId());
					i.putExtras(b);
					startActivityForResult(i, 0);
					break;
				case 1:
					createFavoriteStatus();
					break;
				case 2:
					i = new Intent(mStatusesActivity,
							PersonalInfoActivity.class);
					b = new Bundle();
					b.putString("name", currentItem.getUser().getScreenName());
					b.putString("statuses", currentItem.getUser()
							.getStatusesCount());
					b.putString("followers", currentItem.getUser()
							.getFollowersCount());
					b.putString("friends", currentItem.getUser()
							.getFriendsCount());
					b.putString("profile", currentItem.getUser()
							.getProfileImageUrl());
					b.putString("description", currentItem.getUser()
							.getDescription());
					b.putString("id", currentItem.getUser().getId());
					i.putExtras(b);
					startActivityForResult(i, 0);
					break;
				default:
					break;
				}
			}
		});
		dialog.show();
	}

	private void showMySelectTextMenuDialog() {
		Builder dialog = new AlertDialog.Builder(this);
		String[] sel = {"收藏" };
		dialog.setTitle("对自己");
		dialog.setItems(sel, new Dialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					createFavoriteStatus();
					break;
				default:
					break;
				}
			}
		});
		dialog.show();
	}

	private void createFavoriteStatus() {
		IChangeEvent ice = new IChangeEvent() {

			@Override
			public void changeHandler(boolean success) {
				mStatusesActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(mStatusesActivity, "收藏成功",
								Toast.LENGTH_SHORT).show();
					}
				});
			}
		};
		IErrorEvent iee = new IErrorEvent() {

			@Override
			public void errorHandler() {
				mStatusesActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(mStatusesActivity, "已收藏",
								Toast.LENGTH_SHORT).show();
					}
				});
			}
		};
		mFanfouApi.createFavorite(currentItem.getId(), ice, iee);
	}
}
